package com.magic.goods.service.impl;

import com.magic.goods.service.GoodsHtmlService;
import com.magic.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author lan.jianyuan
 * @create 2021-01-28-11:44
 */
@Service
public class GoodsHtmlServiceImpl implements GoodsHtmlService {
    @Autowired
    private TemplateEngine engine;
    @Autowired
    private GoodsService goodsService;
    @SuppressWarnings("checkstyle:RegexpSinglelineJava")
    @Override
    public void createHtml(Long spuId) {
        // 获取页面数据
        Map<String, Object> spuMap = this.goodsService.loadModel(spuId);
        // 创建thymeleaf上下文对象
        Context context = new Context();
        // 把数据放入上下文对象
        context.setVariables(spuMap);
        // 创建输出流
        PrintWriter writer = null;
        // 把静态文件生成到服务器本地
        File file = new File("D:\\richang\\bishe\\nginx-1.12.1 - bishe\\html\\item\\" + spuId + ".html");
        try {
            writer = new PrintWriter(file);
            // 执行页面静态化方法
            this.engine.process("item", context, writer);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
    
    @Override
    public void deleteHtml(Long spuId) {
        File file = new File("D:\\richang\\bishe\\nginx-1.12.1 - bishe\\html\\item\\" + spuId + ".html");
        file.deleteOnExit();
    }
}
